#include "SDL_include\SDL.h"
#ifdef __WIN32__
#include <Windows.h>
#endif

int EventLoop();
void PutPixel(SDL_Surface* surface, int x, int y, Uint32 color);

int width, height;

SDL_Surface* window_surface;
int main(int argc, char* argv[])
{
	if ( SDL_Init(SDL_INIT_EVERYTHING) < 0 ) {
		exit(1);
	}

	const SDL_VideoInfo* info = SDL_GetVideoInfo();
	Uint8 video_bpp;
	Uint32 videoflags;
	if ( info->vfmt->BitsPerPixel > 8 ) {
		video_bpp = info->vfmt->BitsPerPixel;
	} else {
		video_bpp = 16;
		fprintf(stderr, "forced 16 bpp mode\n");
	}

	videoflags = SDL_HWSURFACE | SDL_RESIZABLE | SDL_FULLSCREEN;

	if ((window_surface = SDL_SetVideoMode(width,height,video_bpp,videoflags)) == NULL) {
		exit(2);
	}
	SDL_WM_SetCaption("Ransact", NULL);	

//#ifdef __WIN32__
//	if(FreeConsole() == 0)
//		exit(3);
//#endif

	EventLoop();
	SDL_Quit();
	return 0;
}


int EventLoop()
{ 
	bool exiting = false;
	SDL_Event event;
	while(!exiting) {
		while( SDL_PollEvent(&event)) {
			switch(event.type) {
					case SDL_QUIT:
						exiting = true;
						break;
					case SDL_KEYDOWN:
						if(event.key.keysym.sym == SDLK_q)
							exiting = true;
						if(event.key.keysym.sym == SDLK_a)

						break;
					case SDL_KEYUP:
						break;
					case SDL_MOUSEMOTION:
						PutPixel(window_surface, event.motion.x, event.motion.y, 255);
						break;
					case SDL_MOUSEBUTTONDOWN:
						break;
					case SDL_MOUSEBUTTONUP:
						break;
			}
		}
		SDL_Delay(10);
		SDL_Flip(window_surface);
	}
	return 0;
}

void PutPixel(SDL_Surface* surface, int x, int y, Uint32 color)
{
	SDL_LockSurface(surface);
	int bpp = surface->format->BytesPerPixel;
	/* Here p is the address to the pixel we want to set */
	
	Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
	
	switch(bpp) {
	case 1:
		*p = color;
		break;

	case 2:
		*(Uint16 *)p = color;
		break;

	case 3:
		if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
			p[0] = (color >> 16) & 0xff;
			p[1] = (color >> 8) & 0xff;
			p[2] = color & 0xff;
		} else {
			p[0] = color & 0xff;
			p[1] = (color >> 8) & 0xff;
			p[2] = (color >> 16) & 0xff;
		}
		break;

	case 4:
		*(Uint32 *)p = color;
		break;
	}
	SDL_UnlockSurface(surface);
}
